package com.teamclub.erp.sservices

import io.ebean.{Ebean, ExpressionList}
import com.teamclub.domain.erp.goods.Goods
import com.teamclub.erp.sforms.ErpGoodsForm
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

@Service
class ErpGoodsService {
  def expr(where: ExpressionList[Goods], form: ErpGoodsForm) = {
    if(form.id != null) {
      where.eq("id", form.id)
    }
    if(StringUtils.isNotBlank(form.organNo)) {
      where.eq("organNo", form.organNo)
    }
    if(StringUtils.isNotBlank(form.name)) {
      where.like("name", "%" + form.name + "%")
    }
  }

  def list(form: ErpGoodsForm): F.Either[Pager[Goods], ErrorCode] = {
    val where = Ebean.find(classOf[Goods]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def add(form: ErpGoodsForm): F.Either[Goods, ErrorCode] = {
    var instance = new Goods
    if(form.id != null) {
      instance = Ebean.find(classOf[Goods], form.id)
    }
    if(instance == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    BeanUtils.copyProperties(form, instance)
    if(form.id == null) {
      instance.save()
    } else {
      instance.update()
    }
    F.Either.Left(instance)
  }

  def del(form: ErpGoodsForm): F.Either[Goods, ErrorCode] = {
    if(form.id == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    val instance = Ebean.find(classOf[Goods], form.id)
    instance.delete()
    F.Either.Left(instance)
  }
}
